package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    /**
     * 添加分类
     */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page<Category>> list(Integer page, Integer pageSize) {
        Page<Category> categoryPage = new Page<>(page,pageSize);
        categoryService.query().orderByAsc("sort").orderByDesc("update_time").page(categoryPage);
        return R.success(categoryPage);
    }

    /**
     * 修改
     * @param category
     * @return
     */
    @PutMapping
     public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return  R.success("修改成功");
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.deleteById(id);
        return R.success("删除成功");
    }
    /**
     * 查询分类
     */
    @GetMapping("list")
    public R<List<Category>> list(Integer type){
        List<Category> list = categoryService.query()
                .orderByDesc("sort")
                .eq(type != null, "type", type)
                .list();
        return R.success(list);
    }

}
